///////////////////////////////////////////////////////////////////////////////
//
// Licensed under the MIT License
//
// Copyright (c) 2010 Chris Colinsky
// All Rights Reserved
//
// version	0.5
// http://code.google.com/p/sugarcookie/
// http://code.google.com/p/sugarcookie/wiki/License
//
////////////////////////////////////////////////////////////////////////////////

package sugarcookie.data.handlers.xml {
	import flash.events.EventDispatcher;
	
	import mx.logging.ILogger;
	import mx.logging.Log;
	import mx.utils.ObjectUtil;
	import mx.utils.StringUtil;
	
	//import sugarcookie.data.DataManager;
	import sugarcookie.data.handlers.IDataHandler;
	import sugarcookie.data.vo.*;
	import sugarcookie.error.ApplicationError;
	import sugarcookie.events.DataEvent;
	import sugarcookie.events.GenericEvent;
	import sugarcookie.file.DataLoader;

	/**
	 * Composites the XMLLoader class and provides an API that works with the sugarcookie XML Schema.
	 */
	public class XHTMLHandler extends EventDispatcher implements IDataHandler {
		private var _log:ILogger;
		private var _isAutoLoad:Boolean;
		private var _id:String = "XHTML";
		private var _xLoader:DataLoader;
		private var _headerXML:DataLoader;
		private var _footerXML:DataLoader;
		private var _htmlURL:String;
		private var _html:XMLList;
		private var _header:Div;
		private var _footer:Div;
		private var _content:Div;
		private var _globalCount:uint = 0;
		private namespace w3 = "http://www.w3.org/1999/xhtml";
        use namespace w3;
        
        public static function cleanHTML(_html:XMLList):String {
        	var str:String = _html.toXMLString();
        	
			var pattern:RegExp = / xmlns="http:\/\/www.w3.org\/1999\/xhtml"/; 
			while (str.search(pattern)>-1) {
				str = str.replace(pattern, "");
			}
			
			var pattern2:RegExp = /<br\/>/; 
			while (str.search(pattern2)>-1) {
				str = str.replace(pattern2, "<br>");
			}
			
			var pattern3:RegExp = /\s<br>\s/; 
			while (str.search(pattern3)>-1) {
				str = str.replace(pattern3, "<br>");
			}
			
			var pattern4:RegExp = /[\t\r\n]/; 
			while (str.search(pattern4)>-1) {
				str = str.replace(pattern4, "");
			}
			
			var pattern5:RegExp = /> /; 
			while (str.search(pattern5)>-1) {
				str = str.replace(pattern5, ">");
			}
			
			var pattern6:RegExp = /\s\s/; 
			while (str.search(pattern6)>-1) {
				str = str.replace(pattern6, " ");
			}
			
			return StringUtil.trim(str);
        }
        
        public function XHTMLHandler(url:String) {
			super(this);
			_log = Log.getLogger("sugarcookie.data.handlers.xml.XHTMLHandler");
			_htmlURL = url;
		}
		
		public function init():void {
			_xLoader = new DataLoader(_htmlURL);
			_xLoader.addEventListener(DataLoader.ERROR,onError,false,0,true);
			_xLoader.addEventListener(DataLoader.STATUS,onStatus,false,0,true);
			_xLoader.addEventListener(DataLoader.COMPLETE,onComplete,false,0,true);
			_xLoader.load();
		}
		
		public function get autoLoad():Boolean { return _isAutoLoad; }
		public function set autoLoad(value:Boolean):void { _isAutoLoad = value; }
		
		public function get id():String { return _id; }
		public function set id(value:String):void { _id = value; }
		
		public function kill():void {
			_xLoader = null;
			_html = null;
		}
		
		public function get content():Div {
			return _content;
		}
		
		private function onError(evt:GenericEvent):void {
			dispatchEvent(new GenericEvent(DataEvent.ON_DATA_CHANNEL_ERROR,false,false,"XHTML",true));
			throw new ApplicationError(String(evt.status));
		}
		
		private function onStatus(evt:GenericEvent):void {
			//could dispatch loading info here
		}
		
		private function onComplete(evt:GenericEvent):void {
			_xLoader.removeEventListener(DataLoader.ERROR,onError);
			_xLoader.removeEventListener(DataLoader.STATUS,onStatus);
			_xLoader.removeEventListener(DataLoader.COMPLETE,onComplete);
			
			var xml:XML = new XML(_xLoader.data as String);
			
			_html = xml.body.div.(@id=="page_container").div.(@id=="swf_container");
			parseHTML();
			if (_isAutoLoad) dispatchEvent(new DataEvent(DataEvent.ON_AUTO_LOAD_COMPLETE,false,false,"XHTML",true));
			else dispatchEvent(new DataEvent(DataEvent.ON_DATA_CHANNEL_RETURN,false,false,"XHTML",true));
		}
		
		private function parseHTML():void {
			_content = new Div(XML(_html..div.(hasOwnProperty("@id") && @id=="content").toXMLString().replace(' xmlns="http://www.w3.org/1999/xhtml"','')));
		}
	}
}